from django.conf import settings
from rest_framework import serializers
from user.models import User
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from django.core.mail import send_mail
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from celery_tasks.email.tasks import send_email
from goods.models import SKU

class UserSerializer(serializers.ModelSerializer):
    # 显示指明验证字段
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    allow = serializers.CharField(write_only=True)
    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('id', 'mobile', 'username', 'password', 'password2', 'sms_code', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'max_length': 20,
                'min_length': 5,
                'error_messages': {
                    'max_length': '名字过长',
                    'min_length': '名字过短'
                }
            },
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
                'error_messages': {
                    'max_length': '密码过长',
                    'min_length': '密码过短'
                }
            },
        }

    # 手机格式判断
    def validate_mobile(self, value):

        if not re.findall(r'1[3-9]\d{9}$', value):
            return serializers.ValidationError('手机格式不正确')

        return value

    # 判断是否选中协议
    def validate_allow(self, value):

        if value != True:
            return serializers.ValidationError('为选中')
        return value

    def validate(self, attrs):
        # 密码判断
        if attrs['password'] != attrs['password2']:
            return serializers.ValidationError('密码不一致')

        # 判断短信
        # 1 先获取缓存中的短信
        conn = get_redis_connection('verify')
        real_sms_code = conn.get('sms_code_%s' % attrs['mobile'])
        if not real_sms_code:
            raise serializers.ValidationError('短信验证码失效')

        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')

        return attrs

    def create(self, validated_data):
        # 删除不需要保存的字段数据
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        # User.objects.create_user()
        user = super().create(validated_data)

        # 明文密码加密
        user.set_password(validated_data['password'])
        user.save()

        # 生产token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 写入token
        user.token = token

        return user


class UserDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email', 'email_active')


class UserEmailSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'email')
        extra_kwargs = {
            'email':{
                'required': True
            }
        }

    def update(self, instance, validated_data):

        instance.email = validated_data['email']

        instance.save()

        # 数据加密
        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps({'id':instance.id, 'username':instance.username}).decode()

        send_email.delay(token, validated_data['email'])

        return instance


class VerifyEmailSerializer(serializers.Serializer):

    token = serializers.CharField(write_only=True)

    def validate(self, attrs):

        # token 解密
        tjs = TJS(settings.SECRET_KEY, 300)

        try:
            data = tjs.loads(attrs['token'])
        except:
            raise serializers.ValidationError('错误的token')

        if not data:
            raise serializers.ValidationError('数据已失效')

        attrs['data'] = data

        data['token'] = attrs['token']

        return attrs


class AddUserBrowsingHistorySerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):

        try:
            SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        return attrs

    def create(self, validated_data):

        user = self.context['request'].user

        sku_id = validated_data['sku_id']

        conn = get_redis_connection('history')

        pl = conn.pipeline()

        pl.lrem('history_%s'%user.id, 0, sku_id)

        pl.lpush('history_%s'%user.id, sku_id)

        pl.ltrim('history_%s'%user.id, 0, 4)

        pl.execute()

        return validated_data